import React, { Component } from 'react'
import PubSubJS from 'pubsub-js'
import './index.css'

export default class Show extends Component {

    state = {
        userInfo: [],
        isFirst: true,
        isLoading: false,
        err: ''
    }

    componentDidMount() {
        // 使用PubSubJS上的subscribe方法进行消息的订阅
        this.token = PubSubJS.subscribe('giveData', (_, data) => {
            this.setState(data)
        })
    }

    componentWillUnmount() {
        // 组件销毁之前，使用PubSubJS上的unsubscribe方法进行消息的取消订阅
        PubSubJS.unsubscribe(this.token)
    }

    render() {
        const {userInfo, isFirst, isLoading, err} = this.state
        return (
            <div className="userContainer">
                {
                    isFirst ? (<h3>输入关键字，点击搜索</h3>) :
                    isLoading ? (<h3>Loading.....</h3>) : 
                    err ? (<h3 style={{color: 'red'}}>{err}</h3>) : 
                    (
                        userInfo.map(item => (
                            <div className="userItem" key={item.id}>
                                <div className="userImg">
                                    <img src={item.avatar_url} alt="headPortrait"/>
                                </div>
                                <div className="userName">
                                    {item.login}
                                </div>
                            </div>
                        ))
                    )
                }
            </div>
        )
    }
}
